package com.elitel.frame.base.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.bind.annotation.RequestParam;

import com.elitel.frame.base.service.DownLoadJarService;
import com.elitel.frame.core.onloadjar.SortableField;
import com.elitel.frame.main.entity.BaseJarinfo;
import com.elitel.frame.main.entity.BaseJarmethod;
import com.elitel.frame.main.entity.ext.Census;

//import com.elitel.frame.main.controller.common.SortableField;



/**
 * 
 * 上传文件处理的控制类
 * @author dingdaifu
 *
 */
@RequestMapping("/system/uploadfile")
@Controller
public class DownLoadFileController {

	@Resource
	private DownLoadJarService downLoadJarServiceImpl;

	private static String DEFAULT_METHOD = "waitequalsnotifynotifyAlltoStringhashCodegetClass";

	@RequestMapping(value = "/upload2")
	@ResponseBody
	public String upload2(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("myFile") MultipartFile myfile) throws IllegalStateException, IOException {
		System.out.println("上传文件开始+++++++++++++++++++++++");
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 判断request里面是否是Multipart类型的数据
		if (multipartResolver.isMultipart(request)) {
			// 把request强制转换成MultipartHttpServletRequest类型的
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

			// 用迭代器去判断里面有多少文件,遍历文件的一个方法
			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				// 迭代器的作用就是一个一个拿文件,把文件拿到
				MultipartFile file = multiRequest.getFile((String) iter.next());
				if (file != null) {
					// 拿到文件之后输出文件
					// 首先定义文件名称
					String fileName = file.getOriginalFilename();
					// 定义输出路径
					String guid = String.valueOf(System.currentTimeMillis());
					///String path = "E:/" + fileName;
					//Modify By CocoLiu 2017/11/14 request.getServletContext()
					String pathing = request.getSession().getServletContext().getRealPath("/WEB-INF/extjar");
					// String fromFilePath = "E:\\" + "EntityTestTwo.jar";
					// pathing = pathing+"\\"+guid+"\\"+fileName;
					pathing = pathing + "\\" + guid;
					// 初始化文件
					File localFile = new File(pathing);
					if (!localFile.exists()) {
						localFile.mkdir();
					}
					//E:\Workspaces\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\frame-main-web\WEB-INF\extjar\1510222807502\tomcat-api.jar
					pathing = pathing + "\\" + fileName;
					String fromFilePath = pathing;
					File localFiles = new File(pathing);
					// 用stringMVC给咱们提供的方法给它写到本地去
					file.transferTo(localFiles);
					BaseJarinfo baseJarinfo = new BaseJarinfo();
					baseJarinfo.setJarName(fileName);
					baseJarinfo.setJarUrl(fromFilePath);
					baseJarinfo.setGuid(guid);
					try {
						int a = downLoadJarServiceImpl.insertBaseJarInfo(baseJarinfo);
						if (a > 0) {
							getJarName(fromFilePath, guid, request, response);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
		return "/success";
	}

	/**
	 * 删除jar包
	 */

	@RequestMapping("/deleteJar")
	@ResponseBody
	public int deleteJar(HttpServletRequest request) {
		String guid = request.getParameter("keys");
		int a = downLoadJarServiceImpl.deleteJar(guid);
		return a;
	}
	
	/**
	 * 读取jar包的类名和属性名
	 * @param jarFile
	 * @param guid
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	public void getJarName(String jarFile, String guid, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 定义一个注解帮助类类型的list
		List<SortableField> list = new ArrayList<SortableField>();
		try {

			// 通过将给定路径名字符串转换为抽象路径名来创建一个新File实例
			File f = new File(jarFile);
			URL realURL = f.toURI().toURL();
			URLClassLoader myClassLoader = new URLClassLoader(new URL[] { realURL },
					Thread.currentThread().getContextClassLoader());

			// 通过jarFile和JarEntry得到所有的类
			JarFile jar = new JarFile(jarFile);
			// 返回zip文件条目的枚举
			Enumeration<JarEntry> enumFiles = jar.entries();
			JarEntry entry;

			// 测试此枚举是否包含更多的元素
			while (enumFiles.hasMoreElements()) {
				entry = (JarEntry) enumFiles.nextElement();
				if (entry.getName().indexOf("META-INF") < 0) { // 在字符串entry中查找"META-INF"首次出现的位置
					String classFullName = entry.getName();
					if (classFullName.indexOf(".class") < 0) { // 在字符串classFullName中查找".class"首次出现的位置
						classFullName = classFullName.substring(0, classFullName.length() - 1);
					} else {
						// 去掉后缀.class
						String className = classFullName.substring(0, classFullName.length() - 6).replace("/", ".");
						String strClassName = className.substring(className.lastIndexOf(".") + 1, className.length());
						System.out.println("最后截取的类名:" + strClassName);
						Class clazz = Class.forName(className);
						System.out.println("++++++++++++++++++++++++++++++");
						Class<?> myclass = myClassLoader.loadClass(className);
						Class<?>[] interfaceses = clazz.getClass().getInterfaces();
						 Method ml[] =clazz.getDeclaredMethods();  
				            System.out.println("遍历获得的方法数组\n");  
				            for (int i = 0 ;i<ml.length;i++)  
				            {  
				                System.out.println("开始遍历第"+(i+1)+"个方法");  
				                Method m = ml[i];  
				                System.out.println("开始获取方法的变量类型");  
				                Class ptype[] = m.getParameterTypes();  
				                for (int j=0; j<ptype.length; j++)  
				                {  
				                    System.out.println("方法参数"+j+"类型为"+ptype[j]);  
				                }  
				                Class gEx[] = m.getExceptionTypes();  
				                for (int j=0 ; j<gEx.length; j++)  
				                {  
				                    System.out.println("异常"+j+"为"+ gEx[j]);  
				                }  
				                  
				                System.out.println("该方法的返回值类型为："+m.getReturnType()+"\n");  
				                  
				            }
//						Field[] fds = clazz.getFields();
//						for (int i=0; i<fds.length; i++)  
//			            {  
//			                String fn = fds[i].getName();  
//			                Class tc = fds[i].getType();  
//			                String ft = tc.getName();  
//			                System.out.println("该属性的名字为："+fn+"，该属性的类型为："+ft);  
//			            }  
//						for (Class<?> class1 : interfaceses) {
//							String interfacename = class1.getName().substring(class1.getName().lastIndexOf(".") + 1,
//									class1.getName().length());
//							System.out.println(interfacename);
//							// if ("BaseJarInter".equals(interfacename)) {
//							Field[] fieldse = clazz.getDeclaredFields();
							Package package1 = myclass.getPackage();
							String packagename = package1.getName();
//							Method m[] = myclass.getMethods();
							List<BaseJarmethod> list2 = new ArrayList<>();
							for (int i = 0; i < ml.length; i++) {
								String sm = ml[i].getName();
								if (DEFAULT_METHOD.indexOf(sm) < 0) {
									System.out.println(sm);
									BaseJarmethod baseJarmethod = new BaseJarmethod();
									baseJarmethod.setClassMethod(sm);
									Thread.sleep(10);
									baseJarmethod.setGuid(String.valueOf(System.currentTimeMillis()));
									baseJarmethod.setClassName(strClassName);
									baseJarmethod.setPackageName(packagename);
									baseJarmethod.setSguid(guid);
									baseJarmethod.setCreatuser("user");
									list2.add(baseJarmethod);
									int as = downLoadJarServiceImpl.insertBaseJarMethodOne(baseJarmethod);
									// System.out.println("~~~~打印方法名：~~~~~" +
									// m[i].toString().substring((m[i].toString().indexOf(className))));
								}
							}
						//}

						// }
						// int a =
						// downLoadJarServiceImpl.insertBaseJarMethod(list2);
						// 根据class对象获得属性
						// Field[] fields = myclass.getDeclaredFields();
						// //这里面获得了四个字段
						// Entities entitiesList = new Entities();

						// 获得类上的注解
						// FieldMeta meta111 =
						// myclass.getAnnotation(FieldMeta.class);
						// System.out.println("类名的中文注释：" + meta111.name());
						// entitiesList.setEntityDesc(meta111.name());
						// //类名的中文描述（中文注释）

						// for(Field f1 : fields){
						// //获取字段中包含fieldMeta的注解
						// FieldMeta meta = f1.getAnnotation(FieldMeta.class);
						// System.out.println("打印长度：" + meta.length());
						// System.out.println("打印 类型：" +
						// f1.getType().getName());
						// String getPropertyType =
						// f1.getType().getName().toString();
						// String strPropertyType =
						// getPropertyType.substring(getPropertyType.lastIndexOf(".")+1,
						// getPropertyType.length());
						// System.out.println("最后截取的属性类型:" + strPropertyType);
						// if(meta!=null){
						// SortableField sf = new SortableField(meta, f1);
						// //System.out.println("字段名称："+l.getName()+"\t字段类型："+l.getType()+"\t注解名称："+l.getMeta().name()+"\t注解描述："+l.getMeta().description());
						// //System.out.println("字段名称："+l.getName());
						// //将属性名和类名添加到实体中
						// // entitiesList.setEntityName(strClassName); //类名
						// // entitiesList.setDataType(strPropertyType); //属性类型
						// //entitiesList.setDataType(meta.getClass().getTypeName());
						// // entitiesList.setDataLength(meta.length()); //长度
						// // entitiesList.setPropertyName(f1.getName()); //属性名
						// // entitiesList.setPropertyDesc(sf.getMeta().name());
						// //属性名的中文描述（中文注释）
						// // entitiesBean.addJarToTable(entitiesList);
						// }
						// }
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 下载接口jar
	@RequestMapping("/download")
	@ResponseBody
	 public ResponseEntity<byte[]> fileDownLoad(HttpServletRequest request) throws Exception{
	     ////E:\Workspaces\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\frame-main-web\WEB-INF\extjar\1510222807502\tomcat-api.jar
		//Modify By CocoLiu 2017/11/14 request.getServletContext() 
		 ServletContext servletContext = request.getSession().getServletContext();
	      String fileName="tomcat-api.jar";
	      String realPath = servletContext.getRealPath("/WEB-INF/extjar/1510222807502/tomcat-api.jar");//得到文件所在位置
	        InputStream in=new FileInputStream(new File(realPath));//将该文件加入到输入流之中
	         byte[] body=null;
	         body=new byte[in.available()];// 返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取（或跳过）的估计剩余字节数
	         in.read(body);//读入到输入流里面
	        
	        fileName=new String(fileName.getBytes("gbk"),"iso8859-1");//防止中文乱码
	        HttpHeaders headers=new HttpHeaders();//设置响应头
	        headers.add("Content-Disposition", "attachment;filename="+fileName);
	        HttpStatus statusCode = HttpStatus.OK;//设置响应吗
	        ResponseEntity<byte[]> response=new ResponseEntity<byte[]>(body, headers, statusCode);
	        return response;
	    }

	@RequestMapping("/getTreeList")
	@ResponseBody
	// 获取左侧树结构 结构为--->jar包名---->包层--->类名--->方法名
	public List<Census> getLoadJar(HttpServletRequest request) {
		List<Census> list = downLoadJarServiceImpl.getLoadJar();
		return list;
	}
}
